package com.atjava.nebula.web.interceptor;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.atjava.nebula.core.tablexml.view.ViewConfig;
import com.atjava.nebula.web.action.BaseViewAction;
import com.atjava.nebula.web.view.XmlViewManager;

public class BaseRequestInterceptor implements HandlerInterceptor {

	private static final String BASEVIEW_URL_REGEXP = 
			"\\/base\\/[^\\/]+\\/[^\\/]+\\/([^\\/]+)/([^\\?\\&\\/\\;\\#]+)";
	
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		String requestUri = request.getRequestURI();
		Pattern p = Pattern.compile(BASEVIEW_URL_REGEXP);
		Matcher mtch = p.matcher(requestUri);
		
		if(mtch.find()){
			String catalog = mtch.group(1);
			String xmlview = mtch.group(2);
			
			ViewConfig config = XmlViewManager.getXmlViewConfig(catalog, xmlview);
			BaseViewAction baseViewAction = (BaseViewAction)handler;
			baseViewAction.setCatalog(catalog);
			baseViewAction.setXmlview(xmlview);
			baseViewAction.setViewConfig(config);
		}
		
		return true;
	}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
		
		//System.out.println("============postHandle" + handler);
	}

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
		//System.out.println("============afterCompletion" + handler);
	}

	
	
}
